package com.heima.user.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.RedisConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;

import com.heima.model.user.pojos.ApUserFollow;

import com.heima.user.mapper.ApUserFollowMapper;

import com.heima.user.service.ApUserFollowService;

import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
@Slf4j
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {




    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 关注方法
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
//        校验参数
        if (dto == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

//        获取用户和作者id，
        Integer userid = AppThreadLocalUtil.getUser().getId();
        Integer authorId = dto.getAuthorId();

//        redis
        if (dto.getOperation() == 0) {
            redisTemplate.opsForHash().put(RedisConstants.USER_ID_ + userid, RedisConstants.AUTHOR_ID_ + authorId, true);
        } else if (dto.getOperation() == 1) {
            Object o = redisTemplate.opsForHash().get(RedisConstants.USER_ID_ + userid, RedisConstants.AUTHOR_ID_ + authorId);
            if (o == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            } else {
                redisTemplate.opsForHash().delete(RedisConstants.USER_ID_ + userid, RedisConstants.AUTHOR_ID_ + authorId);
            }
        }

//        返回参数
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}